/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    ListNode* reverseList(ListNode* head) {
        if (!head)
            return head;
        ListNode* newHead = head;
        ListNode* headNext = newHead->next;
        
        while (headNext)
        {
            ListNode* tmp = headNext->next;
            headNext->next = newHead;
            newHead = headNext;
            headNext = tmp;
        }
        head->next = nullptr;
        return newHead;   
    }
public:
ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* slow = head;
        ListNode* fast = head;
        ListNode* newHead = head;
        int n = k;
        
        //先找到新的头
        while (--n && newHead)
            newHead = newHead->next;
        if (newHead == nullptr)
            return head;

        ListNode* prev;

        while (fast)
        {
            n = k;
            while (--n && fast)
                fast = fast->next;
            if (fast == nullptr)
                break;

            ListNode* Next = fast->next;
            fast->next = nullptr;
            ListNode* revHead = reverseList(slow);
            if (prev)
                prev->next = revHead;
            slow->next = Next;
            prev = slow;
            slow = slow->next;
            fast = slow;
        }
        return newHead;
    }
};